from frame import MyAPP
import guizero
import threading
import pynput
import time
import numpy as np
from PIL import ImageGrab
import os,shutil


class Screen(MyAPP):
    def __init__(self, title, size):
        '初始化'
        MyAPP.__init__(self)
        self.app.title = title
        self.app.width, self.app.height = size
        self.countdownText = guizero.Text(
            self.app, text=5, size=80, color='red')
        guizero.Box(self.app, width='fill', border=1)
        box = guizero.Box(self.app, layout='grid')
        w = 12
        b1 = guizero.PushButton(box, text='设置倒计时(s)', command=self.setCountdown, grid=[
                                0, 1], pady=1, width=w)
        b2 = guizero.PushButton(box, text='设置截屏速度(fps)', command=self.setFps, grid=[
                                1, 1], pady=1, width=w)
        self.countdownTextBox = guizero.TextBox(box, 5, grid=[0, 0], width=2)
        self.fpsTextBox = guizero.TextBox(box, 5, grid=[1, 0], width=2)
        b3 = guizero.PushButton(box, text='设置截屏时长(s)', command=self.setTime, grid=[
                                2, 1, 2, 1], pady=1, width=w)
        self.timeTextBox = guizero.TextBox(box, 5, grid=[2, 0, 2, 1], width=2)
        b4 = guizero.PushButton(box, text='选择截图区域', grid=[
                                0, 2], pady=1, width=w, command=self.setCutArea)
        self.b5 = guizero.PushButton(box, text='开始屏幕截图', grid=[
                                     1, 2, 2, 1], pady=1, width=int(2.4*w), enabled=False, command=self.startCapture)
        self.setCountdown()
        self.setFps()
        self.setTime()

    def setCountdown(self):
        '设置倒计时'
        countdown = self.countdownTextBox.value
        try:
            self.countdown = int(countdown)
        except:
            self.countdown = 5
        self.countdownText.value = self.countdown

    def setFps(self):
        '设置fps'
        fps = self.fpsTextBox.value
        try:
            self.fps = int(fps)
        except:
            self.fps = 5

    def setCutArea(self):
        '设置截图区域'
        self.t = threading.Thread(target=self.selectArea)
        self.t.start()
        self.app.tk.iconify()  # 最小化
        # self.app.tk.state('icon')#最小化方法二

    def selectArea(self):
        'tk最小化时候会停止线程，所以需要子线程操作'
        self.status = 0
        def on_move(x, y):
            print('Pointer moved to {0}'.format((x, y)))
        def on_click(x, y, button, pressed):
            if pressed:  # 按下时
                if self.status == 0:
                    self.startPoint = (x, y)
                    self.status = 1
            if not pressed:  # 松开时
                if self.status == 1:
                    self.endPoint = (x, y)
                    return False
        def on_scroll(x, y, dx, dy):
            print('Scrolled {0} at {1}'.format(
                'down' if dy < 0 else 'up',
                (x, y)))
        # Collect events until released
        with pynput.mouse.Listener(on_click=on_click) as listener:
            listener.join()
        self.app.tk.deiconify()  # 取消最小化
        # self.app.tk.lift()#取消最小化方法二
        self.app.tk.attributes("-topmost", True)  # 最上层
        guizero.info('提示', f'截图区域设置成功:\n{(self.startPoint,self.endPoint)}')
        self.b5.enable()

    def setTime(self):
        '设置时长'
        recTime = self.timeTextBox.value
        try:
            self.recTime = int(recTime)
        except:
            self.recTime = 5

    def startCapture(self):
        self.t.join()
        n = self.countdown

        def startCount():
            for i in range(self.countdown):
                time.sleep(1)
                self.countdownText.value = self.countdown-1-i
            self.app.tk.iconify()  # 最小化
            self.b5.disable()
            self.capture()
        self.t = threading.Thread(target=startCount)
        self.t.start()

    def capture(self):
        '开始截屏'
        self.setTime()
        self.setFps()
        self.setCountdown()
        start=time.time()    
        dirName=str(int(start))
        dirName=os.path.join(self.path,dirName)
        if os.path.isdir(dirName):
            shutil.rmtree(dirName)
        if os.path.isfile(dirName):
            os.remove(dirName)
        os.makedirs(dirName)
        self.ims=[]
        before=time.time()
        start=time.time()
        while time.time()-start<=self.recTime:
            if time.time()-before>1/self.fps:
                im=ImageGrab.grab(bbox=list(self.startPoint)+list(self.endPoint))
                self.ims.append(im)
                before=time.time()
        i=0
        for im in self.ims:
            im.save(os.path.join(dirName,f'{i}.png'))
            i+=1
        self.app.tk.deiconify()  # 取消最小化
        # self.app.tk.lift()#取消最小化方法二
        self.app.tk.attributes("-topmost", True)  # 最上层
        guizero.info('提示','截图完毕！')
        self.countdownText.value=self.countdown
        self.b5.enable()


if __name__ == '__main__':
    app = Screen('截图大师', (400, 220))
    app.display()
